from urllib.parse import quote
from urllib import request
import json
import numpy as np
import matplotlib.pyplot as plt
import geohash
from bd09_2_wgs84 import gcj02_to_wgs84

amap_web_key = 'f7e5f805c9d8038065a11cf544144d94'
poi_search_url = "http://restapi.amap.com/v3/place/text"
cityname = "湖北省"
keywords = "湖北省"

i = 1
poilist = []
while True:
    page = i
    req_url = poi_search_url + "?key=" + amap_web_key + '&extensions=all&keywords=' + quote(
        keywords) + '&city=' + quote(cityname) + '&citylimit=true' + '&offset=25' + '&page=' + str(
        page) + '&output=json'
    print(req_url)
    with request.urlopen(req_url) as f:
        data = f.read()
        data = data.decode('utf-8')
    result = data
    result = json.loads(result)  # 将字符串转换为json
    if result['count'] == '0':
        break
    poilist.extend(result['pois'])
    i = i + 1
    if i > 0:
        break
pois = poilist
id = pois[0]['id']

req_url = f'https://gaode.com/service/poiInfo?query_type=IDQ&pagesize=20&pagenum=1' \
    f'&qii=true&cluster_state=5&need_utd=true' \
    f'&utd_sceneid=1000&div=PC1000&addr_poi_merge=true&is_classify=true&zoom=11&id={id}'
print(req_url)

f = request.urlopen(req_url)
data = f.read()
data = data.decode('utf-8')
dataList = []
datajson = json.loads(data)  # 将字符串转换为json
datajson = datajson['data']
datajson = datajson['poi_list']
datalatlng_ls = datajson[-1]['domain_list'][-1]['value']
print(datalatlng_ls)

arr = np.array([[float(a.split(',')[0]), float(a.split(',')[1])] for a in datalatlng_ls.split('_')])
xmin, xmax = min(arr[:, 0]), max(arr[:, 0])
ymin, ymax = min(arr[:, 1]), max(arr[:, 1])
step = min(ymax-ymin, xmax-xmin)/10
xv, yv = np.arange(xmin, xmax, step), np.arange(ymin, ymax, step)
xv1, yv1 = np.meshgrid(xv, yv)
xv2, yv2 = xv1.reshape(-1), yv1.reshape(-1)

plt.plot(arr[:, 0], arr[:, 1])
for (x, y), s in zip(arr, map(str, range(len(arr)))):
    plt.text(x, y, s)
plt.plot(xv2, yv2, '*')
plt.show()

def isRayIntersectsSegment(poi, s_poi, e_poi):  # [x,y] [lng,lat]
    # 输入：判断点，边起点，边终点，都是[lng,lat]格式数组
    # print(poi, s_poi, e_poi)
    if s_poi[1] == e_poi[1]:  # 排除与射线平行、重合，线段首尾端点重合的情况
        return False
    if s_poi[1] > poi[1] and e_poi[1] > poi[1]:  # 线段在射线上边
        return False
    if s_poi[1] < poi[1] and e_poi[1] < poi[1]:  # 线段在射线下边
        return False
    if s_poi[0] < poi[0] and e_poi[0] < poi[0]:  # 线段在射线左边
        return False
    if s_poi[1] == poi[1] and e_poi[1] > poi[1]:  # 交点为spoint
        return False
    if e_poi[1] == poi[1] and s_poi[1] > poi[1]:  # 交点为epoint
        return False
    xseg = e_poi[0] - (e_poi[0] - s_poi[0]) * (e_poi[1] - poi[1]) / (e_poi[1] - s_poi[1])  # 求交
    if xseg < poi[0]:  # 交点在射线起点的左侧
        return False
    return True  # 排除上述情况之后


def isPoiWithinPoly(poi, epoly):
    sinsc = 0  # 交点个数
    for i in range(len(epoly)):  # [0,len-1]
        s_poi = epoly[i]
        e_poi = epoly[(i+1) % len(epoly)]
        if isRayIntersectsSegment(poi, s_poi, e_poi):
            sinsc += 1  # 有交点就加1
    return True if sinsc % 2 == 1 else False


sel = []
xy_arr = np.array([xv2, yv2]).T
for xy in xy_arr:
    sel += [isPoiWithinPoly(xy, arr)]


plt.plot(arr[:, 0], arr[:, 1])
for (x, y), s in zip(arr, map(str, range(len(arr)))):
    plt.text(x, y, s)
plt.plot(xy_arr[sel, 0], xy_arr[sel, 1], '*')
plt.show()

res_arr = xy_arr[sel]
# np.apply_along_axis(gcj02_to_wgs84, 1, res_arr)

geo_ls = []
for (lng, lat) in res_arr:
    lng84, lat84 = gcj02_to_wgs84(lng, lat)
    print(lng, lat, '\n', lng84, lat84)
    geo_ls += [geohash.encode(lat84, lng84)]

print(';'.join(geo_ls))